/*
 * Copyright 2010 - 2011, The PLDesktop Development Team
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

#include "spinlock.h"

#include <machine/pc/processor/processor.h>
#include <kerneldebugconsole.h>
#include <assert.h>

Spinlock::Spinlock(bool bLocked, bool bAvoidTracking) : m_bInterrupts(),
	m_atom(!bLocked), m_Ra(0), m_bAvoidTracking(bAvoidTracking), m_Magic(0xdeadbaba) {
}

void Spinlock::acquire() {
	bool bInterrupts = PLProcessor::instance().interrupts();
	PLKernelDebugConsole &output = PLKernelDebugConsole::instance();
	if(bInterrupts) {
		PLProcessor::instance().setInterrupts(false);
	}
	if(m_Magic != 0xdeadbaba) {
		output.printf("\nWrong magic in acquire. %x\n", m_Magic);
	}
	while(m_atom.compareAndSwap(true, false) == false) {
		output.printf("\nSpinlock has deadlocked in acquire.");
		assert(false);
	}
	m_Ra = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
	m_bInterrupts = bInterrupts;
}

void Spinlock::release() {
	bool bWasInterrupts = PLProcessor::instance().interrupts();
	PLKernelDebugConsole &output = PLKernelDebugConsole::instance();
	if(bWasInterrupts == true) {
		output.printf("\nSpinlock: release() called with interrupts enabled.\n");
	}
	bool bInterrupts = m_bInterrupts;
	if(m_atom.compareAndSwap(false, true) == false) {
		output.printf("\nSpinlock has deadlocked in release.");
		assert(false);
	}
	if(bInterrupts) {
		PLProcessor::instance().setInterrupts(true);
	}
	if(m_Magic != 0xdeadbaba) {
		output.printf("\nWrong magic in release. %x\n", m_Magic);
	}
}
